package com.study.family;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectAuthCredential;
import com.huawei.agconnect.auth.PhoneAuthProvider;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hmf.tasks.TaskExecutors;
import com.study.family.cdb.CdbActivity;
import com.study.family.third.HWIDActivity;

import java.util.Locale;

public  class LoginActivity extends Activity implements View.OnClickListener {

    private EditText accountEdit;
    private EditText verifyCodeEdit;
    private LinearLayout galleryLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //已登陆过，则直接进入主界面
        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            startActivity(new Intent(this, CdbActivity.class));
            finish();
        }
        initView();
    }
    private void initView() {
        accountEdit = findViewById(R.id.phone_account);
        verifyCodeEdit = findViewById(R.id.verify_code);

        Button loginBtn = findViewById(R.id.btnlogin);
        loginBtn.setOnClickListener(this);

        Button send = findViewById(R.id.btn_send);
        send.setOnClickListener( this);
        galleryLayout = findViewById(R.id.id_gallery);
        findViewById(R.id.btn_login_anonymous).setOnClickListener( this);
        initThird();
    }

    private void initThird() {
        int[] ids = getResources().getIntArray(R.array.ids);
        TypedArray typedArray = getResources().obtainTypedArray(R.array.ids);//获得任意类型
        String[] names = getResources().getStringArray(R.array.names);
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < ids.length; i++) {
            View view = inflater.inflate(R.layout.layout_imge, galleryLayout, false);
            ImageView img = view.findViewById(R.id.image);
            img.setImageResource(typedArray.getResourceId(i, R.mipmap.huawei));
            TextView text = view.findViewById(R.id.text);
            text.setText(names[i]);
            view.setOnClickListener(new ThirdListener(names[i]));
            galleryLayout.addView(view);
        }
    }

    public class ThirdListener implements View.OnClickListener {
        private String name;

        ThirdListener(String name) {
            this.name = name;
        }

        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (name) {
                case "Huawei ID":
                    intent = new Intent(LoginActivity.this, HWIDActivity.class);

                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnlogin:
                login();
                break;
            case R.id.btn_send:
                sendVerificationCode();
                break;
            case R.id.btn_login_anonymous:
                loginAnonymous();
                break;
        }
    }

    private void sendVerificationCode() {
        VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
                .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
                .sendInterval(30) //最短发送间隔 ，30
                .locale(Locale.SIMPLIFIED_CHINESE)
                .build();

            String phoneNumber = accountEdit.getText().toString().trim();
            int cd =86;
            String countryCode=Integer.toString(cd);
            Task<VerifyCodeResult> task =  AGConnectAuth.getInstance().requestVerifyCode(countryCode, phoneNumber, settings);
            task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
                @Override
                public void onSuccess(VerifyCodeResult verifyCodeResult) {
                    Toast.makeText(LoginActivity.this, "发送手机验证码成功", Toast.LENGTH_SHORT).show();
                    //手机接收验证码成功
                }
            }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    Toast.makeText(LoginActivity.this, "申请验证码失败:" + e, Toast.LENGTH_SHORT).show();
                }
            });
        }


    private void login() {
            String phoneNumber = accountEdit.getText().toString().trim();
            String verifyCode = verifyCodeEdit.getText().toString().trim();
            AGConnectAuthCredential credential;
            //如果你没有密码，password可以为null，86为中国代码
            int cd=86;
            String countryCode=Integer.toString(cd);

            credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, null, verifyCode);
            signIn(credential);
        }

    private void signIn(AGConnectAuthCredential credential) {
        AGConnectAuth.getInstance().signIn(credential)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        startActivity(new Intent(LoginActivity.this, CdbActivity.class));

                        LoginActivity.this.finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "登录失败:" + e, Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private void loginAnonymous() {
        // signIn anonymously
        AGConnectAuth.getInstance().signInAnonymously()
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        Intent intentnext=new Intent();
                        intentnext.setClass(LoginActivity.this,CdbActivity.class);
                        startActivity(intentnext);

                        LoginActivity.this.finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "匿名登录失败:" + e, Toast.LENGTH_SHORT).show();
                    }
                });
    }
}